package com.example.administrator.ygddriver.into.register;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.ygddriver.MainActivity;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseBean;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.LogInformationBean;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.login.driverjoin.DriverJoinActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.audit.AuditActivity;
import com.example.administrator.ygddriver.into.register.forget.ForGetActivity;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.liteorm.SingleLiteOrm;
import com.example.administrator.ygddriver.netty.TcpClient;
import com.example.administrator.ygddriver.tool.IsPhoneNum;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.litesuits.orm.db.impl.CascadeSQLiteImpl.TAG;

/**
 * 登录界面
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private SimpleToolbar simpleToolbar;
    private TextView mVerificationOnTv, mPasswordOnTv, mForGetTv;
    private RelativeLayout mVerificationOnRL, mPasswordOnRl, mNextRl;
    private ImageView mEyesIv, mAccountDelIv, mPasswordDelIv, mAccountVerificationDelIv;
    private EditText mAccountEt, mPasswordEt, mVerificationEt, mPhoneNumEt;
    private Button mGetVerificationBtn;
    private String status;
    //判断为验证码还是密码登录
    private int tag = 0;
    private CountDownTimer timer;


    @Override
    public int initLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        simpleToolbar = findViewById(R.id.activity_register_stb);
        mVerificationOnRL = findViewById(R.id.activity_register_verification_rl);
        mPasswordOnRl = findViewById(R.id.activity_register_rl);
        mVerificationOnTv = findViewById(R.id.activity_register_verification_tv);
        mPasswordOnTv = findViewById(R.id.activity_register_password_tv);
        mEyesIv = findViewById(R.id.activity_register_eyes_iv);
        mAccountDelIv = findViewById(R.id.activity_register_account_del_iv);
        mPasswordDelIv = findViewById(R.id.activity_register_password_del_iv);
        mAccountVerificationDelIv = findViewById(R.id.activity_register_account_verification_del_iv);
        mAccountEt = findViewById(R.id.activity_register_account_et);
        mPasswordEt = findViewById(R.id.activity_register_password_et);
        mPhoneNumEt = findViewById(R.id.activity_register_phone_num_et);
        mVerificationEt = findViewById(R.id.activity_register_verification_et);
        mForGetTv = findViewById(R.id.activity_register_forget_tv);
        mNextRl = findViewById(R.id.activity_register_next_rl);
        mGetVerificationBtn = findViewById(R.id.activity_register_get_verification_btn);
        mGetVerificationBtn.setOnClickListener(this);
        mPasswordOnTv.setOnClickListener(this);
        mVerificationOnTv.setOnClickListener(this);
        mEyesIv.setOnClickListener(this);
        mAccountDelIv.setOnClickListener(this);
        mPasswordDelIv.setOnClickListener(this);
        mAccountVerificationDelIv.setOnClickListener(this);
        mForGetTv.setOnClickListener(this);
        mNextRl.setOnClickListener(this);
    }

    @Override
    public void initDate() {
        setSimpleToolbar();
        addEt();
    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("登录");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.u126);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_register_password_tv:
                mVerificationOnRL.setVisibility(View.GONE);
                mPasswordOnRl.setVisibility(View.VISIBLE);
                tag = 0;
                break;
            case R.id.activity_register_verification_tv:
                mVerificationOnRL.setVisibility(View.VISIBLE);
                mPasswordOnRl.setVisibility(View.GONE);
                tag = 1;
                break;
            case R.id.activity_register_eyes_iv:
                mPasswordEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                break;
            case R.id.activity_register_account_del_iv:
                mAccountEt.setText("");
                break;

            case R.id.activity_register_password_del_iv:
                mPasswordEt.setText("");
                break;
            case R.id.activity_register_account_verification_del_iv:
                mPhoneNumEt.setText("");
                break;
            case R.id.activity_register_forget_tv:
                Intent intent = new Intent(this, ForGetActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_register_next_rl:
                if (tag == 0) {
                    if (judge(mAccountEt.getText().toString(), mPasswordEt.getText().toString(), null)) {
                        initDoLoginHtml(mAccountEt.getText().toString(), mPasswordEt.getText().toString(), "1");
                    }
                } else {
                    if (judge(mPhoneNumEt.getText().toString(), null, mVerificationEt.getText().toString())) {
                        initDoLoginHtml(mPhoneNumEt.getText().toString(), mVerificationEt.getText().toString(), "2");
                    }

                }


                break;
            case R.id.activity_register_get_verification_btn:
                startTime();
                if (IsPhoneNum.isPhoneNumber(String.valueOf(mPhoneNumEt.getText()))) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("c_phone", String.valueOf(mPhoneNumEt.getText()));
                    params.put("type", "4");
                    initGetVerificationHtml(params);
                } else {
                    timer.cancel();
                    BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", "请输入正确电话号码");
                    baseHint.show();
                }
                break;

        }
    }

    private void startTime() {
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerificationBtn.setClickable(false);
                mGetVerificationBtn.setText((millisUntilFinished / 1000) + "秒");
            }

            @Override
            public void onFinish() {
                mGetVerificationBtn.setClickable(true);
                mGetVerificationBtn.setText("获取验证码");
            }
        }.start();


    }

    private void addEt() {
        mAccountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAccountDelIv.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mAccountEt.getText())) {
                    mAccountDelIv.setVisibility(View.GONE);
                } else {
                    mAccountDelIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mAccountEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(mAccountEt.getText())) {
                        mAccountDelIv.setVisibility(View.GONE);
                    } else {
                        mAccountDelIv.setVisibility(View.VISIBLE);
                    }
                } else {
                    mAccountDelIv.setVisibility(View.GONE);
                }
            }
        });
        mPasswordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPasswordDelIv.setVisibility(View.VISIBLE);
                mEyesIv.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mPasswordEt.getText())) {
                    mPasswordDelIv.setVisibility(View.GONE);
                    mEyesIv.setVisibility(View.GONE);
                } else {
                    mPasswordDelIv.setVisibility(View.VISIBLE);
                    mEyesIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPasswordEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(mPasswordEt.getText())) {
                        mPasswordDelIv.setVisibility(View.GONE);
                        mEyesIv.setVisibility(View.GONE);
                    } else {
                        mPasswordDelIv.setVisibility(View.VISIBLE);
                        mEyesIv.setVisibility(View.VISIBLE);
                    }
                } else {
                    mPasswordDelIv.setVisibility(View.GONE);
                    mEyesIv.setVisibility(View.GONE);
                }
            }
        });
        mPhoneNumEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAccountVerificationDelIv.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mPhoneNumEt.getText())) {
                    mAccountVerificationDelIv.setVisibility(View.GONE);
                } else {
                    mAccountVerificationDelIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPhoneNumEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(mPhoneNumEt.getText())) {
                        mAccountVerificationDelIv.setVisibility(View.GONE);
                    } else {
                        mAccountVerificationDelIv.setVisibility(View.VISIBLE);
                    }
                } else {
                    mAccountVerificationDelIv.setVisibility(View.GONE);
                }
            }
        });
    }

    //登录
    private void initDoLoginHtml(String c_account, String c_password, String c_logintype) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_account", c_account);
        if (c_logintype.equals("2")) {
            hashMap.put("c_code", c_password);
        } else {
            hashMap.put("c_password", c_password);
        }
        hashMap.put("c_type", UrlValuse.TYPE);
        hashMap.put("c_logintype", c_logintype);
        hashMap.put("c_registrationid", JPushInterface.getRegistrationID(this));
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.DO_LOGIN, hashMap, RegisterRequestBean.class, new OkGoRequests.OnTrue<RegisterRequestBean>() {
            @Override
            public void hasData(final RegisterRequestBean date) {
                if (date.isSuccess()) {
                    saveUserMessage(date.getResult());
                    status = date.getResult().getC_status();
                    driverInfoHtml(date.getResult().getC_id(), date.getResult().getC_token());
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<RegisterRequestBean>() {
            @Override
            public void noData() {

            }
        });


    }

    //司机端用户基本信息查询
    private void driverInfoHtml(String c_id, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_INFO, hashMap, DriverInfoRequestBean.class, new OkGoRequests.OnTrue<DriverInfoRequestBean>() {
            @Override
            public void hasData(final DriverInfoRequestBean date) {
                if (date.isSuccess()) {
                    LiteOrmTools.getInformation(LogInformationBean.class, RegisterActivity.this, new LiteOrmTools.On<LogInformationBean>() {
                        @Override
                        public void hasData(LogInformationBean data) {
                            data.setC_status(date.getResult().getDriverinfo().getC_status());
                            data.setC_account(date.getResult().getDriverinfo().getC_account());
                            data.setC_city(date.getResult().getDriverinfo().getC_city());
                            data.setC_create_time(date.getResult().getDriverinfo().getC_create_time());
                            data.setC_driverlicense(date.getResult().getDriverinfo().getC_driverlicense());
                            data.setC_drivingdate(date.getResult().getDriverinfo().getC_drivingdate());
                            data.setC_drivertype(date.getResult().getDriverinfo().getC_drivertype());
                            data.setC_drivinggrade(date.getResult().getDriverinfo().getC_drivinggrade());
                            data.setC_frontface(date.getResult().getDriverinfo().getC_frontface());
                            data.setC_id(date.getResult().getDriverinfo().getC_id());
                            data.setC_handheld(date.getResult().getDriverinfo().getC_handheld());
                            data.setC_worknumber(date.getResult().getDriverinfo().getC_worknumber());
                            data.setC_idnumber(date.getResult().getDriverinfo().getC_idnumber());
                            data.setC_licensenumber(date.getResult().getDriverinfo().getC_licensenumber());
                            data.setC_models(date.getResult().getDriverinfo().getC_models());
                            data.setC_name(date.getResult().getDriverinfo().getC_name());
                            data.setC_wechat(date.getResult().getDriverinfo().getC_wechat());
                            data.setC_create_time(date.getResult().getDriverinfo().getC_create_time());
                            data.setC_vehicleowner(date.getResult().getDriverinfo().getC_vehicleowner());
                            data.setC_vehicledate(date.getResult().getDriverinfo().getC_vehicledate());
                            data.setC_reverseside(date.getResult().getDriverinfo().getC_reverseside());
                            data.setC_vehiclelicense(date.getResult().getDriverinfo().getC_vehiclelicense());
                            data.setC_onecarphoto(date.getResult().getDriverinfo().getC_onecarphoto());
                            data.setC_headportrait(date.getResult().getDriverinfo().getC_headportrait());
                            data.setC_order(date.getResult().getDriverinfo().getC_order());
                            data.setC_opinion(date.getResult().getDriverinfo().getC_opinion());
                            SingleLiteOrm.getSingleLiteOrm(RegisterActivity.this).SingleLite().update(data);
                        }
                    }, new LiteOrmTools.OFF() {
                        @Override
                        public void noData() {
                            LogInformationBean data = new LogInformationBean();
                            data.setC_status(date.getResult().getDriverinfo().getC_status());
                            data.setC_account(date.getResult().getDriverinfo().getC_account());
                            data.setC_city(date.getResult().getDriverinfo().getC_city());
                            data.setC_create_time(date.getResult().getDriverinfo().getC_create_time());
                            data.setC_driverlicense(date.getResult().getDriverinfo().getC_driverlicense());
                            data.setC_drivingdate(date.getResult().getDriverinfo().getC_drivingdate());
                            data.setC_drivertype(date.getResult().getDriverinfo().getC_drivertype());
                            data.setC_drivinggrade(date.getResult().getDriverinfo().getC_drivinggrade());
                            data.setC_frontface(date.getResult().getDriverinfo().getC_frontface());
                            data.setC_id(date.getResult().getDriverinfo().getC_id());
                            data.setC_handheld(date.getResult().getDriverinfo().getC_handheld());
                            data.setC_worknumber(date.getResult().getDriverinfo().getC_worknumber());
                            data.setC_idnumber(date.getResult().getDriverinfo().getC_idnumber());
                            data.setC_licensenumber(date.getResult().getDriverinfo().getC_licensenumber());
                            data.setC_models(date.getResult().getDriverinfo().getC_models());
                            data.setC_name(date.getResult().getDriverinfo().getC_name());
                            data.setC_wechat(date.getResult().getDriverinfo().getC_wechat());
                            data.setC_create_time(date.getResult().getDriverinfo().getC_create_time());
                            data.setC_vehicleowner(date.getResult().getDriverinfo().getC_vehicleowner());
                            data.setC_vehicledate(date.getResult().getDriverinfo().getC_vehicledate());
                            data.setC_reverseside(date.getResult().getDriverinfo().getC_reverseside());
                            data.setC_vehiclelicense(date.getResult().getDriverinfo().getC_vehiclelicense());
                            data.setC_onecarphoto(date.getResult().getDriverinfo().getC_onecarphoto());
                            data.setC_headportrait(date.getResult().getDriverinfo().getC_headportrait());
                            data.setC_order(date.getResult().getDriverinfo().getC_order());
                            data.setC_opinion(date.getResult().getDriverinfo().getC_opinion());
                            SingleLiteOrm.getSingleLiteOrm(RegisterActivity.this).SingleLite().insert(data);
                        }
                    });

                    if (status.equals("3")) {
                        Intent intent = new Intent(RegisterActivity.this, AuditActivity.class);
                        intent.putExtra("status", "3");
                        startActivity(intent);
                        finish();
                    } else if (status.equals("0")) {
                        Intent intent = new Intent(RegisterActivity.this, DriverJoinActivity.class);
                        startActivity(intent);
                        finish();

                    } else if (status.equals("2")) {
//                        timer.start();
                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();

                    } else if (status.equals("1")) {
                        Intent intent = new Intent(RegisterActivity.this, AuditActivity.class);
                        intent.putExtra("status", "1");
                        startActivity(intent);
                        finish();
                    }

                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<DriverInfoRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    private void saveUserMessage(final RegisterRequestBean.ResultBean resultBean) {
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                data.setC_token(resultBean.getC_token());
                data.setC_id(resultBean.getC_id());
                data.setC_account(resultBean.getC_account());
                SingleLiteOrm.getSingleLiteOrm(RegisterActivity.this).SingleLite().update(data);
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {
                UserBean userBean1 = new UserBean();
                userBean1.setC_token(resultBean.getC_token());
                userBean1.setC_id(resultBean.getC_id());
                userBean1.setC_account(resultBean.getC_account());
                SingleLiteOrm.getSingleLiteOrm(RegisterActivity.this).SingleLite().insert(userBean1);
            }
        });

    }

    private Boolean judge(String account, String password, String code) {
        if (!IsPhoneNum.isPhoneNumber(account)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", "请输入正确的手机账号");
            baseHint.show();
            return false;
        }
        if (!TextUtils.isEmpty(password) && password.length() < 6 && TextUtils.isEmpty(code)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", "密码长度错误");
            baseHint.show();
            return false;
        }
        if (!TextUtils.isEmpty(code) && code.length() < 6) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", "验证码错误");
            baseHint.show();
            return false;
        }

        return true;
    }

    //获取验证码
    private void initGetVerificationHtml(HashMap<String, String> params) {
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.CREATE_VERIFICATION_CODE, params, BaseBean.class, new OkGoRequests.OnTrue<BaseBean>() {
            @Override
            public void hasData(BaseBean data) {
                if (data.isSuccess()) {

                } else {
                    timer.cancel();
                    mGetVerificationBtn.setClickable(true);
                    mGetVerificationBtn.setText("获取验证码");
                    BaseHint baseHint = new BaseHint.addHint().setParameter(RegisterActivity.this, "提示", data.getLocalizedMessage());
                    baseHint.show();
                }

            }
        }, new OkGoRequests.OnError<BaseBean>() {
            @Override
            public void noData() {

            }
        });


    }


}
